package com.jianying.day04;

import com.jianying.beans.WaterSensor;
import com.jianying.func.WaterSensorMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * ClassName: Flink03_Split_Stream
 * Package: com.atguigu.day04
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/2 10:30
 * @Version: 1.0
 */
public class Flink04_Split_Stream_SideOutput {
    public static void main(String[] args) throws Exception {
//        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        DataStreamSource<String> socketDS = env.socketTextStream("localhost", 8888);
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> mapDS = socketDS.map(
                new WaterSensorMapFunction()
        );

        // TODO 分流
        // 定义侧输出流标签
        OutputTag<WaterSensor> ws1Tag = new OutputTag<WaterSensor>("ws1"){};
        OutputTag<WaterSensor> ws2Tag = new OutputTag<WaterSensor>("ws2", Types.POJO(WaterSensor.class));
        // 分流 需要用到上下文对象，只能调用底层处理函数process
        SingleOutputStreamOperator<WaterSensor> mainDS = mapDS.process(
                new ProcessFunction<WaterSensor, WaterSensor>() {
                    @Override
                    public void processElement(WaterSensor value, ProcessFunction<WaterSensor, WaterSensor>.Context ctx, Collector<WaterSensor> out) throws Exception {
                        String id = value.getId();
                        if ("ws1".equals(id)) {
                            // 将数据打上标记
                            ctx.output(ws1Tag, value);
                        } else if ("ws2".equals(id)) {
                            ctx.output(ws2Tag, value);
                        } else {
                            out.collect(value);
                        }
                    }
                }
        );

        SideOutputDataStream<WaterSensor> ds1 = mainDS.getSideOutput(ws1Tag);
        SideOutputDataStream<WaterSensor> ds2 = mainDS.getSideOutput(ws2Tag);

        mainDS.print("main");
        ds1.print("ws1");
        ds2.print("ws2");


        env.execute();
    }
}
